package com.yejq.http.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yejq.util.PropertiesUtils;

public class BingbingProcessor implements Processor {

	private Socket socket;
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	public BingbingProcessor() {
	}
	
	public BingbingProcessor(Socket socket){
		this.socket = socket;
	}

	public void run() {
		InputStream inputStream = null;
		PrintStream outputStream = null;
		try {
			logger.info("冰冰为您服务……");
			inputStream = socket.getInputStream();
			outputStream = new PrintStream(socket.getOutputStream());
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			String line = reader.readLine();
			logger.info("request: {}", line);
			
			if (line == null || line.length() == 0) {
				outputStream.println("HTTP/1.1 400 query error");
				outputStream.println();
				outputStream.flush();
				return;
			}
			
			String[] lineStrings = line.split(" ");
			if (lineStrings.length != 3) {
				outputStream.println("HTTP/1.1 400 query error");
				outputStream.println();
				outputStream.flush();
				return;
			}else {
				String path = PropertiesUtils.getString("webapps") + lineStrings[1];
				logger.debug("path:{}", path);
				
				File file = new File(path);
				if (file.exists()) {
					byte[] content = new byte[(int)file.length()];
					FileInputStream fis = new FileInputStream(file);
					fis.read(content);
					
					outputStream.println("HTTP/1.1 200 OK");
					outputStream.println("Content-Type:text/html");
					outputStream.println("Content-Length: " + content.length);
					outputStream.println();
					outputStream.write(content);
					outputStream.flush();
					
					fis.close();
				}else {
					outputStream.println("HTTP/1.1 404 file not found");
					outputStream.println();
					outputStream.flush();
					return;
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if (outputStream != null) {
				outputStream.close();
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
